<?php
namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\library\TencentSin;
use app\common\library\TencentSms;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Sms\V20210111\SmsClient;
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use think\Request;
/**
 * 短信发送接口
 */
class Sms extends Api
{
    // 无需登录的接口
    protected $noNeedLogin = "*";
    // 无需鉴权的接口
    protected $noNeedRight ="*";

    /**
     * 发送短信
     * 验证码模板ID：2222343
     * {1}为您的验证码，请于{2}分钟内填写，如非本人操作，请忽略本短信。
     *
     * @ApiTitle    (发送短信)
     * @ApiSummary  (通过腾讯云短信发送验证码)
     * @ApiMethod   (POST)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号码")
     * @ApiParams   (name="template_id", type="string", required=true, description="短信模板ID")
     * @ApiParams   (name="params", type="array", required=true, description="模板参数数组")
     * @ApiParams   (name="sign_name", type="string", required=true, description="短信签名")
     * @ApiReturn   ({
     *     "code": 1,
     *     "msg": "短信发送成功",
     *     "data": null
     * })
     */
    public function send()
    {
        // 获取请求参数
        $mobile =$this->request->post('phone');
        $params = $this->request->post('params/a'); // 接收数组参数
         try {
             $r=model("Sms")->where("mobile",$mobile)->where("code",$_REQUEST["code"])->find();
            if (isset($r)) {
                $this->success('输入验证码正确');
            } else {
                $this->error('输入验证码错误');
            }
        }
        catch(TencentCloudSDKException $e) {
            echo $e;
        }
    }

    public function sendSms(Request $request)
    {
        // 获取请求参数
        $phone = $_REQUEST['phone'];
        $event = $_REQUEST['event'];

        if (!$phone || !preg_match('/^1[3-9]\d{9}$/', $phone)) {
            // 第67行 - 手机号格式不正确
            return json(['code' => 400, 'msg' => '手机号格式不正确']);

            // 第96行 - 验证码发送失败
            return json(['code' => 500, 'msg' => '验证码发送失败：' . $resp->SendStatusSet[0]->Message]);

            // 第109行 - 验证码发送成功
            return json(['code' => 200, 'msg' => '验证码发送成功']);
        }

        // 生成随机验证码
        $code = rand(1000, 9999);

        // 调用腾讯云短信服务发送验证码
        try {
            $smsConfig = config('sms');
            $cred = new Credential($smsConfig['SecretId'], $smsConfig['SecretKey']); // 替换为您的腾讯云密钥
            $client = new SmsClient($cred, "ap-guangzhou"); // 替换为您所在的区域
            $req = new SendSmsRequest();
            $templateId = $smsConfig['template_id'];
            $signName = $smsConfig['sign_name'];
            $sdkAppId = $smsConfig['sdkAppId'];
            $endpoint = $smsConfig['endpoint'];


            $params = [
                "PhoneNumberSet" => ["+86" . $phone], // 手机号
                "SmsSdkAppId" => $sdkAppId,
                "TemplateId" => $templateId,
                "SignName" => $signName,
                "TemplateParamSet" => array("{$code}","5"),       // 验证码
            ];

            $req->fromJsonString(json_encode($params));
            $resp = $client->SendSms($req);
            if ($resp->SendStatusSet[0]->Code !== 'Ok') {
                return json(['code' => 0, 'msg' => '验证码发送失败：' . $resp->SendStatusSet[0]->Message]);
            }

            // 记录验证码到数据库或缓存
            $data=array(
                "event"=>$event,
                "mobile"=>$phone,
                "code"=>$code,
                "createtime"=>time(),
                "ip"=>$request->ip(),
                "times"=>0,
            );
            model("Sms")->insertUpdate($data,["event","mobile"]);
            return json(['code' => 0, 'msg' => '验证码发送成功']);
        } catch (\Exception $e) {
            return json(['code' =>0, 'msg' => '验证码发送失败：' . $e->getMessage()]);
        }
    }
}

